package com.jeeplus.test.jlnu.admissionInfo.utils;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.metadata.GlobalConfiguration;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CustomDateConverter implements Converter<Date> {

    // 定义支持的日期格式
    private static final String[] DATE_FORMATS = new String[] {
        "yyyy", "yyyy-MM-dd", "yyyy/MM/dd", "MM/dd/yyyy", "yyyy/M/d H:mm:ss"
    };

    @Override
    public Class<?> supportJavaTypeKey() {
        return Date.class;
    }

    @Override
    public WriteCellData<?> convertToExcelData(Date value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(value);
        return new WriteCellData<>(formattedDate);
    }

    @Override
    public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String dateStr = cellData.getStringValue();

        // 尝试按不同格式解析日期
        for (String format : DATE_FORMATS) {
            try {
                return new SimpleDateFormat(format).parse(dateStr);
            } catch (ParseException e) {
                // 忽略这个异常，继续尝试其他格式
            }
        }

        // 如果都不匹配，抛出异常或返回 null
        throw new IllegalArgumentException("无法解析日期: " + dateStr);
    }
}